package com.usian.controller;

import com.usian.feign.StudentFeign;
import com.usian.pojo.Result;
import com.usian.pojo.Student;
import com.usian.pojo.Teacher;
import com.usian.pojo.TeacherS;
import com.usian.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired
    private TeacherService teacherService;

    @Autowired
    private StudentFeign studentFeign;

    @Autowired
    private LoadBalancerClient loadBalancerClient;  // 自动获取地址

    @RequestMapping("update/{sname}/{id}")
    public Result update(@PathVariable Integer sname,@PathVariable Integer id){
        teacherService.update(sname,id);
        return new Result();
    }

    @PostMapping("add")
        public Result add(@RequestBody TeacherS teacherS){
        Teacher teacher= teacherS.getTeacher();
        List<Student> studentList = teacherS.getStudentList();
        String sname=studentList.get(0).getId()+"";
        for (int i = 1; i <studentList.size() ; i++) {
            sname=sname+","+ studentList.get(i).getId();
        }
        teacher.setSname(sname);
        // http://192.168.1.155:8181/getUserById/1
        for (Student student : studentList) {
            student.setTid(teacher.getId());
            studentFeign.addAll(student);
        }
        teacherService.add(teacher);
        return new Result();
    }
    @GetMapping("delete/{id}")
    public Result delete(@PathVariable Integer id){
        //192.168.1.155
        teacherService.delete(id);
        studentFeign.update(id);
        return new Result();
    }

    @GetMapping("find/{id}")
    public Map<String,Object> find(@PathVariable Integer id){
       Teacher teacher = teacherService.select(id);
        List<Student> students = studentFeign.select(id);
        Map<String,Object> map=new HashMap<>();
        map.put("teacher",teacher);
        map.put("students",students);
        return map;
    }
}
